package com.fejal.dao;


import java.util.List;
import com.fejal.bean.Banco;


public class BancoDAOHibernate implements BancoDAO {

	HibernateDAOFactory hibernateDAOFactory = null;
	HibernateDAO<Banco> hibernateDAO = null;

	public BancoDAOHibernate() {
		hibernateDAOFactory = new HibernateDAOFactory();
		hibernateDAO = hibernateDAOFactory.getBancoDao();
	}

	@Override
	public boolean inserir(Banco banco) throws Exception {

		boolean ok = false;

		try {
			hibernateDAO.add(banco);
			ok = true;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}

		return ok;
	}

	@Override
	public boolean alterar(Banco banco) throws Exception {

		boolean ok = false;
	
		
		try {
			hibernateDAO.update(banco);
			ok = true;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} 
		return ok;
	}

	@Override
	public boolean excluir(Banco banco) throws Exception {

		boolean ok = false;

		try {
			hibernateDAO.remove(banco);
			ok = true;

		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}

		return ok;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Banco> getSelecionar(String descricao) {
		String 	sql = "FROM Banco WHERE codigoBanco <> '0'";

		if (!(descricao.isEmpty())) {
			sql += "AND descricao like '" + descricao + "%' ";  
		}
		
		sql += "ORDER BY descricao";		
 
		List<Banco> lista = hibernateDAO.getSession().createQuery(sql).list();
		return lista;
	}

	@Override
	public Banco getBanco(int codigoBanco) {
		
		Banco banco = hibernateDAO.get(codigoBanco);
		return banco;
	}

	@Override
	public List<Banco> getListTodos() {
		
		List<Banco> list = hibernateDAO.listAll();
		return list;
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public boolean isExiste(Banco banco) {

		String 	sql = 	"FROM Banco " +
				"WHERE descricao	= '"+banco.getDescricao()+"' AND " +
				"		codigoBanco != '"+banco.getCodigoBanco()+"'";

		List<Banco> lista = hibernateDAO.getSession().createQuery(sql).list();
		if(lista.size()<1){
			return false;
		} else {
			return true;
		}
	}

}
